package com.bank.service;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bank.common.Cgenerator;
import com.bank.common.Ngenerator;

@Service("generateCardService")
@Transactional
public class GenerateCardService{
	protected static Logger logger = Logger.getLogger("service");
	ArrayList<String> arrl = new ArrayList<String>();
	
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;
	
	public void setPrevNumbers(ArrayList<String> arrl){
		this.arrl = arrl;	
	}
	
	public ArrayList<String> getCard(){

		ArrayList<String> costomerCard = new ArrayList<String>();	
		Cgenerator cg = new Cgenerator();
		cg.setCodeNumbers(arrl);
		Cgenerator.createCodeCard();
		costomerCard = cg.getCard();
		return costomerCard;
	}
	public Integer getNumber(){
		Ngenerator ng = new Ngenerator();
		String number = new String();
		number = ng.createUserNumber();
		int userNumber = Integer.parseInt(number);
		return userNumber;	
	}
	
	public List<String> saveCardNumbers(int customerID){
		Session session = sessionFactory.getCurrentSession();
		List<String> codes = this.getCard();
		Query query = session.createSQLQuery("DELETE FROM customer_codes " +
    			"WHERE customer_id="+customerID);
    	query.executeUpdate();		
    	int count = 0;
    	for (String code : codes) {
			count++;
			Query newQuery = session.createSQLQuery("INSERT INTO `customer_codes` ( `CUSTOMER_CODE_ID` , `CUSTOMER_CODE_NUMBER` , `CUSTOMER_CODE_VALUE` , `CUSTOMER_ID` ) VALUES ( NULL , '" + count + "', '" + code + "', '" + customerID + "' );");
			newQuery.executeUpdate();
			System.out.println("Size is " + codes.size());
			System.out.println(newQuery);
			System.out.println("ID: " + customerID + "  Number: " + code);
		}
		
		return codes;
	}

	

	
}